package com.datechange.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.w3c.dom.Document;

public class CurrentTimeServiceUtil {
	private static DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
	public static void main(String[] name) {
		getCurrentDateFromInternet();
	}
	public static Date getCurrentDateFromInternet() {
		XmlUtil xmlUtil = new XmlUtil();
		Date currentDate = null;
		try {

			URL url = new URL("http://webservice.theknot.com/Time/GetTime.asmx/currentTime");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setRequestProperty("Accept", "application/xml");
			if (conn.getResponseCode() != 200) {
				throw new RuntimeException("Failed : HTTP error code : "+ conn.getResponseCode());
			}
			BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
			String output;
			StringBuilder xmlString = new StringBuilder();
			while ((output = br.readLine()) != null) {
				xmlString.append(output);
			}
			Document currentTimeDoc = xmlUtil.getXMLFromString(xmlString.toString());
			//currentTimeDoc.getDocumentElement().normalize();
			String[] dateNTime = currentTimeDoc.getDocumentElement().getTextContent().split(" ");
			try {
				currentDate = df.parse(dateNTime[0]);
			} catch (ParseException e) {
				e.printStackTrace();
			}

			conn.disconnect();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return currentDate;
	}



}